using System;
using System.Collections;
using System.Collections.Generic;
using MyFrame.Event;
using MyFrame.Pool;
using MyFrame.Single;
using Plugin.Tool;
using UnityEngine;
using UnityEngine.Audio;
using UnityEngine.SceneManagement;



public class SoundMgr : SingletonMonoGlobal<SoundMgr>
{
    [Header("音乐数据库")]
    public SoundDetailListSO soundListData;
    public SceneSoundListSO sceneSoundData;
    [Header("音源")]
    public AudioSource ambientSource;
    public AudioSource backgroundSource;

    private Coroutine soundRoutine;

    [Header("快照")]
    public AudioMixerSnapshot normalSnapShot;
    public AudioMixerSnapshot ambientSnapShot;
    public AudioMixerSnapshot muteSnapShot;

    [Header("音频混合")]
    public AudioMixer audioMixer;

    private float musicTransitionTime = 3f;

    public float MusicStartSceond => UnityEngine.Random.Range(3f, 6f);

    private void Awake()
    {
        soundListData = AAMgr.LoadAsset<SoundDetailListSO>("SoundDetailListSO");
        // sceneSoundData = AAMgr.LoadAsset<SceneSoundListSO>("SceneSoundListSO");
    }

    private void OnEnable()
    {
        EventCenter.Instance.On(EventEnum.AfterSceneLoad, OnAfterSceneLoad);
        EventCenter.Instance.On(EventEnum.BeforeSceneLoad, OnBeforeSceneLoad);
        EventCenter.Instance.On<SoundName>(EventEnum.PlayerSound, PlayPlayerSound);
        EventCenter.Instance.On(EventEnum.EndGame, OnEndGame);
    }

    private void OnDisable()
    {
        EventCenter.Instance.Off(EventEnum.AfterSceneLoad, OnAfterSceneLoad);
        EventCenter.Instance.Off(EventEnum.BeforeSceneLoad, OnBeforeSceneLoad);
        EventCenter.Instance.Off<SoundName>(EventEnum.PlayerSound, PlayPlayerSound);
        EventCenter.Instance.Off(EventEnum.EndGame, OnEndGame);
    }

    private void OnEndGame()
    {
        if (soundRoutine != null) StopCoroutine(soundRoutine);
        muteSnapShot.TransitionTo(1f);
    }

    /// <summary>
    /// 用事件播放
    /// </summary>
    /// <param name="name"></param>
    private void PlayPlayerSound(SoundName name)
    {
        var sound = soundListData.GetSoundDetails(name);
        if (sound != null)
        {
            var obj = PoolMgr.Instance.GetObj("Sound");
            obj.GetComponent<Sound>().SetSound(sound);
            ZTimer.SetTimeout(sound.currentClip.length, () => PoolMgr.Instance.Release(obj));
        }
    }

    private void OnBeforeSceneLoad()
    {
        backgroundSource.Stop();
        if (ambientSource != null) ambientSource.Stop();
        if (soundRoutine != null) StopCoroutine(soundRoutine);
    }

    private void OnAfterSceneLoad()
    {
        string currentScene = SceneManager.GetActiveScene().name;
        SceneSoundItem sceneSoundItem = sceneSoundData.GetSceneSoundItem(currentScene);

        var ambient = soundListData.GetSoundDetails(sceneSoundItem.ambient);
        var music = soundListData.GetSoundDetails(sceneSoundItem.music);

        if (soundRoutine != null) StopCoroutine(soundRoutine);
        soundRoutine = StartCoroutine(PlaySoundRoutine(music, ambient));
    }

    private IEnumerator PlaySoundRoutine(SoundDetails music, SoundDetails ambient)
    {
        if (music != null && ambient != null)
        {
            if (ambient.soundName == SoundName.None)
            {
                PlayMusicClip(music, 1f);
            }
            else
            {
                // 快速切换到ambient轨道
                PlayAmbientClip(ambient, 1f);
                yield return new WaitForSeconds(MusicStartSceond);
                PlayMusicClip(music, musicTransitionTime);
            }
        }
    }

    private void PlayMusicClip(SoundDetails soundDetails, float transitionTime)
    {
        audioMixer.SetFloat("MusicVolume", Tool.ConvertSoundVolume(soundDetails.volume));
        backgroundSource.clip = soundDetails.RandomClip;
        backgroundSource.Play();

        normalSnapShot.TransitionTo(transitionTime);
    }

    private void PlayAmbientClip(SoundDetails soundDetails, float transitionTime)
    {
        var test = audioMixer.SetFloat("AmbientVolume", Tool.ConvertSoundVolume(soundDetails.volume));

        ambientSource.clip = soundDetails.RandomClip;
        ambientSource.Play();

        ambientSnapShot.TransitionTo(transitionTime);
    }


    //获取声音详情
    public SoundDetails GetSoundDetails(SoundName soundName)
    {
        return soundListData.GetSoundDetails(soundName);
    }

    public void SetMasterVolume(float volume)
    {
        audioMixer.SetFloat("MasterVolume", Tool.ConvertSoundVolume(volume));
    }

}

